#include "candidateitem.h"

#include <QFont>
#include <QStyleOption>
#include <QPainter>

CandidateItem::CandidateItem(int index, const PinyinCandidate &cand, QWidget *parent)
	: QLabel(parent)
    , m_candidate(cand)
    , m_index(index)
{
	// init default style
	m_defaultStyle = R"(QLabel { 
		padding: 6px 12px;
		font-size: 14px; 
		color: #333333; 
		border-radius: 4px;
	})";
    m_hoverStyle = R"(QLabel { 
		padding: 6px 12px; 
		font-size: 14px; 
		color: #333333; 
		background-color: #F5F7FA; 
		border-radius: 4px;
	})";
    m_selectedStyle = R"(QLabel { 
		padding: 6px 12px; 
		font-size: 14px; 
		color: white; 
		background-color: #1890FF; 
		border-radius: 4px; 
	})";

	// show 序号（加粗）+ 文本 + 拼音（小号灰色）
	QFont normalFont = font();
	QFont boldFont = font();
	boldFont.setBold(true);
	QString text = QString("<span style='font-family:%1; font-weight:bold;'>%2. </span>")
                   .arg(boldFont.family()).arg(index + 1)
                   + QString("<span style='font-family:%1;'>%2</span>")
                   .arg(normalFont.family()).arg(cand.text)
                   + QString("<span style='font-family:%1; font-size:10px; color:#999999; margin-left:8px;'>[%2]</span>")
                   .arg(normalFont.family()).arg(cand.pinyin);

    setText(text);
	setStyleSheet(m_defaultStyle);
	setAlignment(Qt::AlignCenter);
}

void CandidateItem::enterEvent(QEvent *event)
{
	Q_UNUSED(event);
	setStyleSheet(m_hoverStyle);
}

void CandidateItem::leaveEvent(QEvent *event)
{
	Q_UNUSED(event);
    setStyleSheet(m_defaultStyle);
}

void CandidateItem::mousePressEvent(QMouseEvent *event)
{
	Q_UNUSED(event);
	if (event->button() == Qt::LeftButton)	emit candidateSelected(m_candidate.text);
}

// 重写paintEvent确保样式生效（QLabel自定义样式需此步骤）
void CandidateItem::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
    QLabel::paintEvent(event);
}